package com.starblink.android.guang

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.imgpreload.PreloadResImgUtils
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.basic.storage.SkStorage
import com.starblink.rocketreserver.AssignExperimentGroupMutation
import com.starblink.rocketreserver.CheckIsExistCategoryQuery
import com.starblink.rocketreserver.FetchResourceConfigQuery
import com.starblink.rocketreserver.FetchSiteQuery
import com.starblink.rocketreserver.HasSubscriptionMessageQuery
import com.starblink.rocketreserver.RegisterDeviceMutation
import com.starblink.rocketreserver.fragment.SiteVOF
import com.starblink.rocketreserver.type.ExperimentRequest
import com.starblink.rocketreserver.type.SiteRequest
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class MainViewModel : BaseViewModel() {

    val subsLD = MutableLiveData<Boolean>()

    /**
     * 校验是否有类目
     */
    fun checkIsExistCategory() {
        viewModelScope.async {
            val response = SkGqlClient.skQuery(
                CheckIsExistCategoryQuery(),
                showFailToast = false,
                showErrorToast = false
            )
            UserDataCenter.loadedCategory = true
            if (response?.data != null) {
                UserDataCenter.existCategory = response.data!!.checkIsExistCategory == true
            }
        }

        if (SkStorage.getString("assign_product_card", "").isNullOrEmpty()) {
            viewModelScope.async {
                val response = SkGqlClient.skMutation(
                    AssignExperimentGroupMutation(
                        experiment = ExperimentRequest(
                            experimentCode = Optional.present(
                                "product_card"
                            )
                        )
                    ),
                    showFailToast = false,
                    showErrorToast = false
                )
                UserDataCenter.loadedCategory = true
                if (response?.data != null && response.data!!.assignExperimentGroup?.experimentVOF?.groupCode != null) {
                    Log.e(
                        "TAG",
                        "experimentVOF: ${response.data!!.assignExperimentGroup?.experimentVOF}"
                    )
                    SkStorage.put(
                        "assign_product_card",
                        response.data!!.assignExperimentGroup?.experimentVOF?.groupCode ?: ""
                    )
//                response.data!!.assignExperimentGroup.experimentVOF.id == true
                }
            }
        }
    }


    // 开机屏 和 首页弹窗 图片预热缓存   3 开机屏图片 4 首页广告图片
    fun getResourceScreenOrHomeImage() {

        if (PreloadResImgUtils.cacheIsEmpty(PreloadResImgUtils.LAUNCH_PAGE)) {
            viewModelScope.async {
                var launchImgs = SkGqlClient.skQuery(
                    FetchResourceConfigQuery(
                        resourceType = Optional.present(3),
                        operationFeaturedSize = Optional.present(4),
                    ),
                    showFailToast = false,
                    showErrorToast = false
                    //fetchPolicy = FetchPolicy.NetworkFirst
                )?.data?.fetchResourceConfig
                if (!launchImgs.isNullOrEmpty()) {
                    launchImgs.forEach { cfg ->
                        val url = cfg?.resourceF?.mainPic
                        val jumpUrl = cfg?.resourceF?.jumpUrl
                        if (!url.isNullOrBlank() && !jumpUrl.isNullOrBlank()) {
                            PreloadResImgUtils.imgPreload(
                                cfg.resourceF,
                                PreloadResImgUtils.LAUNCH_PAGE
                            )
                        }
                    }

                }
            }
        }

        if (PreloadResImgUtils.cacheIsEmpty(PreloadResImgUtils.HOME_ADVERT)) {
            viewModelScope.async {
                var homeAdImgs = SkGqlClient.skQuery(
                    FetchResourceConfigQuery(
                        resourceType = Optional.present(4),
                        operationFeaturedSize = Optional.present(4),
                    ),
                    showFailToast = false,
                    showErrorToast = false
                    //fetchPolicy = FetchPolicy.NetworkFirst
                )?.data?.fetchResourceConfig
                if (!homeAdImgs.isNullOrEmpty()) {
                    homeAdImgs.forEach { cfg ->
                        val url = cfg?.resourceF?.mainPic
                        if (!url.isNullOrBlank()) {
                            PreloadResImgUtils.imgPreload(
                                cfg.resourceF,
                                PreloadResImgUtils.HOME_ADVERT
                            )
                        }
                    }
                }
            }
        }
    }


    fun getSite(siteCallBack: ((site: SiteVOF?) -> Unit)) {
        viewModelScope.async {
            val response = SkGqlClient.skQuery(
                FetchSiteQuery(
                    param = SiteRequest()
                ),
                showFailToast = false,
                showErrorToast = false
            )

            if (response?.data?.fetchSite == null) {
                siteCallBack.invoke(null)
            } else {
                siteCallBack.invoke(response.data!!.fetchSite.siteVOF)
            }
        }
    }

    fun syncSubsInfo() {
        viewModelScope.launch {
            SkGqlClient.skMutation(RegisterDeviceMutation())
        }
        loadHasNewSubs()
    }

    fun loadHasNewSubs() {
        viewModelScope.launch {
            val res =
                SkGqlClient.skQuery(HasSubscriptionMessageQuery())?.data?.hasSubscriptionMessage
            subsLD.postValue(res == true)
        }
    }

}